package org.example.面向对象.db;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBManager {
    public static Connection getConnection1(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (ClassNotFoundException e){
            System.out.println("没有找到驱动！");
        }
        try {
            String url = "jdbc:mysql://localhost:3306/bd2005?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
            String username = "root";
            String password = "a123456";
            conn = DriverManager.getConnection(url,username,password);
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
        return conn;
    }
    public static Connection getConnection(){
        Connection conn = null;
        InputStream in = DBManager.class.getClassLoader().getResourceAsStream("dbcp.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            DataSource dataSource = BasicDataSourceFactory.createDataSource(p);
            conn = dataSource.getConnection();
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return conn;
    }

    public static void closeConnection(Connection conn, PreparedStatement ps,ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
            ps.close();
            conn.close();
        }catch (SQLException e){
            System.out.println(e.getMessage());
        }
    }

}
